<?php
/**
 * Created by PhpStorm.
 * User: janke
 * Date: 17-3-22
 * Time: 下午1:11
 */

namespace app\controllers;

use app\models\LogOutForm;
use app\models\User;
use app\models\SignUpForm;
use yii\filters\auth\QueryParamAuth;
use yii\rest\ActiveController;
use yii\web\IdentityInterface;
use yii\web\Response;
use app\models\LoginForm;

class UserController extends ActiveController
{

    public $modelClass = 'app\models\User';
    public $serializer = [
        'class' => 'yii\rest\Serializer',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'optional' => [
                'login',
                'signup',
            ],
        ];
        return $behaviors; // TODO: Change the autogenerated stub
    }

    /**
     * 登录，第一次登录自动注册
     * @return array
     * @author Janke
     */
    public function actionLogin()
    {
        $postData = \Yii::$app->request->post();
        $model = new LoginForm();
        $model->setAttributes($postData);
        if ($user = $model->login()) {
            if ($user instanceof IdentityInterface) {
                $user->updateIsLogin($user);
                $userMsg['user'] = User::findByUsername($user->username);
                $userMsg['firstLogin'] = 0;
                return $userMsg;
            }
        } else {
            try {
                $respon = $this->actionSignup($postData);
            } catch (\Exception $e) {
                $respon = null;
            }
            return $respon ? $respon : $model->errors;
        }
        return $model->errors;
    }

    /**
     * 自动注册控制器，注册成功后登录
     * @param $postData
     * @return bool
     * @author Janke
     */
    private function actionSignup($postData)
    {
        // 注册且登录
        $userName = $postData['username'];
        $passWord = $postData['password'];
        if ((!SignUpForm::findByUserName($postData['username'])) && strlen($userName) == 12)
        {
            exec("/usr/bin/python3 /home/janke/Projects/PycharmProjects/AuthenticateSCAU/index.py $userName $passWord", $ret, $flag);
//            print_r($ret);
            if ($flag && $ret[0])
            {
                // 注册
                $trueName = $ret[0] ? $ret[0] : null;
                $postData['truename'] = $trueName;
                $postData['z_passwd'] = $passWord;
                $signUpFormModel = new SignUpForm();
                if ($signUpFormModel->signUp($postData))
                {
                    $userMsg['user'] = User::findByUsername($userName);
                    User::updateIsLogin($userMsg['user']);
                    $userMsg['firstLogin'] = 1;
                    return $userMsg;
                }
            }
            return false;
        }
        return false;
    }

    /**
     * 用户登出
     * 更改islogin字段
     * 登出用户重复登出会失败
     * @return array
     * @author Janke
     */
    public function actionLogout()
    {
        $postData = \Yii::$app->request->post();
        $logOutModel = new LogOutForm();
        $logOutModel->setAttributes($postData);
        $result = $logOutModel->validate();
        $user = $logOutModel->attributes;
        if ($result)
        {
            $result = User::updateIsLogout($user['userName']);
        }
        return [
            'LogOutSuccess' => $result
            ];
    }


}